﻿using System;
using System.Linq.Expressions;
using Telerik.Windows.Data;

namespace jSLCore.Client.Presentation.TelerikSupport.Controls
{
    public class TextFilterDescriptor : FilterDescriptorBase
    {
        private readonly bool _caseSensitive;

        public TextFilterDescriptor()
        {
        }

        public TextFilterDescriptor(string path, string parameter, bool caseSensitive)
        {
            _caseSensitive = caseSensitive;
            Path = path;
            Parameter = parameter;
        }

        public string Path { get; set; }

        public string Parameter { get; set; }

        public override Expression CreateFilterExpression(Expression instance)
        {
            var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
            
            var someValue = Expression.Constant(_caseSensitive? Parameter : Parameter.ToLower(), typeof(string));

            var getProperty = Expression.Property(instance,Path);
            if (_caseSensitive)
            {
                var containsMethodExp = Expression.Call(getProperty, containsMethod, someValue);
                return containsMethodExp;
            }
            else
            {
                var lowerMethod = typeof(string).GetMethod("ToLower", new Type[0]); 
                var toLower = Expression.Call(getProperty, lowerMethod);
                var containsMethodExp = Expression.Call( toLower, containsMethod, someValue);
                return containsMethodExp;
            }
        }

        protected override Expression CreateFilterExpression(ParameterExpression parameterExpression)
        {
            return CreateFilterExpression(parameterExpression);
        }
    }
}